package pl.com.like.sequoia.web.beans.upload;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.richfaces.event.UploadEvent;
import org.richfaces.model.UploadItem;

import pl.com.like.sequoia.web.service.IUploadHelperService;
import pl.com.like.sequoia.web.vo.UpFile;

public class FileUploadBean implements Serializable {

	private static final long serialVersionUID = 89764327L;
	private IUploadHelperService uploadHelperService;
	private List<UpFile> upFiles = new ArrayList<UpFile>();
	private int uploadsAvailable = 5;
	private boolean autoUpload = false;
	private boolean useFlash = false;

	public FileUploadBean() {
	}

	public String clearUploadData() {
		upFiles.clear();
		setUploadsAvailable(5);
		return null;
	}

	public List<UpFile> getFiles() {
		return upFiles;
	}

	public int getSize() {
		if (getFiles().size() > 0) {
			return getFiles().size();
		} else {
			return 0;
		}
	}

	public long getTimeStamp() {
		return System.currentTimeMillis();
	}

	public IUploadHelperService getUploadHelperService() {
		return uploadHelperService;
	}

	public int getUploadsAvailable() {
		return uploadsAvailable;
	}

	public boolean isAutoUpload() {
		return autoUpload;
	}

	public boolean isUseFlash() {
		return useFlash;
	}

	public void listener(UploadEvent event) throws Exception {
		UploadItem item = event.getUploadItem();
		UpFile upFile = new UpFile();
		upFile.setLength(item.getData().length);
		upFile.setName(item.getFileName());
		upFile.setData(item.getData());
		upFiles.add(upFile);
		uploadHelperService.saveFacesUploadedInfo(upFile, null);
		uploadsAvailable--;
	}

	public void paint(OutputStream stream, Object object) throws IOException {
		stream.write(getFiles().get((Integer) object).getData());
	}

	public void setAutoUpload(boolean autoUpload) {
		this.autoUpload = autoUpload;
	}

	public void setFiles(ArrayList<UpFile> upFiles) {
		this.upFiles = upFiles;
	}

	public void setUploadHelperService(IUploadHelperService uploadHelperService) {
		this.uploadHelperService = uploadHelperService;
	}

	public void setUploadsAvailable(int uploadsAvailable) {
		this.uploadsAvailable = uploadsAvailable;
	}

	public void setUseFlash(boolean useFlash) {
		this.useFlash = useFlash;
	}

}